﻿/// <reference path="../_reference.js" />
(function (Page) {
    /// 筛选
    /// fn:{Function} return:{String}
    Array.prototype.screen = function (fn) {
        if (!fn) return this;
        var a = [];
        for (var i = 0, len = this.length; i < len; i++) {
            fn(this[i]) !== "" && a.push(fn(this[i]));
        }
        return a;
    }

    var gameid = $("#game").val();
    /// year:Number, 要查询的(农历)年份
    /// num :String, 要查询的球号,如果多个号码则用逗号分隔
    /// type:Number, 1返回(Array)生肖 2返回(String)家禽/野兽
    function getZodiac(year, num, type) {
        //num % 12  将号码转换成1-12,得出在数组对应的索引
        var zodiac = ["鼠", "牛", "虎", "兔", "龙", "蛇", "马", "羊", "猴", "鸡", "狗", "猪"];
        var cate = {
            "鼠,虎,兔,龙,蛇,猴,": "野兽",
            "牛,马,羊,鸡,狗,猪,": "家禽"
        };
        var reference = 1924;///必须是鼠年，即reference对应zodiac[0]
        var index = (year - reference) % 12;
        var a = zodiac.slice(0, index + 1).reverse();
        var b = zodiac.slice(index + 1).reverse();
        var sortZodiac = a.concat(b);
        var result = [];
        if (type === 1) {
            var nums = num.split(',');
            for (var i = 0, len = nums.length; i < len; i++) {
                result.push({
                    num: Number(nums[i]),
                    name: sortZodiac[(nums[i] - 1) % 12]
                });
            }
        } else if (type === 2) {
            if (Number(num) === 49) return '<span>和</span>';
            for (var i in cate) {
                i.indexOf(sortZodiac[(Number(num) - 1) % 12]) > -1 && result.push("<span class='" + (cate[i] === "野兽" ? 'f_c_r' : 'f_c_b') + "'>" + cate[i] + "</span>");
            }
            return result[0];
        }
        return result;
    }

    /// 色波
    function color(num) {
        var arr = [",1,2,7,8,12,13,18,19,23,24,29,30,34,35,40,45,46,", ",3,4,9,10,14,15,20,25,26,31,36,37,41,42,47,48,", ",5,6,11,16,17,21,22,27,28,32,33,38,39,43,44,49,"]
        var arrCn = ["红波", "蓝波", "绿波"];
        var color = ["bg_red", "bg_blue", "bg_green"];
        var index = 0;
        $.each(arr, function (a, b) {
            b.indexOf(',' + num + ',') > -1 && (index = a);
        });
        return { name: arrCn[index], color: color[index] };
    }

    /// 求和
    function compute(arr) {
        var c = 0;
        $.each(arr, function (a, b) {
            c += Number(b);
        });
        return c;
    }

    /// fn:{Function}筛选号码的函数，返回下盘或偶数的数组
    /// length:{Number}参与上下奇偶的号码个数
    /// type:{String} oddeven：上下   updown：奇偶
    /// 相同规则：上下或者奇偶的个数相同则为和
    function three(arr, fn, length, type) {
        var text = [];
        if (type === "oddeven") {
            text = ['偶', '奇'];
        } else if (type === "updown") {
            text = ['下', '上'];
        }

        var len1 = arr.screen(fn).length, len2 = length / 2;
        if (len1 === len2) {
            return '<span>和</span>';
        } else if (len1 > len2) {
            return '<span class="f_c_b">' + text[0] + '</span>';
        } else {
            return '<span class="f_c_r">' + text[1] + '</span>';
        }
    }

    /// 标签的拼接
    /// txt:{String} 显示的文本
    /// type:{String} b:蓝色 r:红色 undefined:无色
    function showTag(txt, type) {
        if (type === undefined) {
            return '<span>' + txt + '</span>';
        } else {
            return "<span class='f_c_" + type + "'>" + txt + "</span>";
        }
    }

    /// id:{String}     对应游戏的属性
    /// item:{Object}   服务端返回的原始对象
    /// arr:{Array}     球号
    var ExtendAttr = {
        SIX: function (item, arr) {
            var obj = {};
            obj.sumBigSmall = bigSmall(item.sum, 175, "zhi", { big: "总大", small: "总小" });
            obj.balls = getZodiac(item.year, item.result, 1);

            var special = item.result.match(/\d+$/)[0] * 1
                    , specialComb = compute(String(special).split(''));
            var he = showTag("和");
            obj.specialOddEven = special === 49 ? he : (special % 2 === 0 ? showTag("特双", "b") : showTag("特单", "r"));
            obj.specialBigSmall = special === 49 ? he : (special >= 25 ? showTag("特大", "b") : showTag("特小", "r"));
            obj.specialCombOddEven = special === 49 ? he : (specialComb % 2 === 0 ? showTag("合双", "b") : showTag("合单", "r"));
            obj.specialCombBigSmall = special === 49 ? he : (specialComb > 6 ? showTag("合大", "b") : showTag("合小", "r"));
            obj.specialLastNum = special === 25 ? he : (specialComb % 10 >= 5 ? showTag("合尾大", "b") : showTag("合尾小", "r"));
            obj.specialAnimal = special === 49 ? he : getZodiac(item.year, special, 2);
            obj.specialColor = color(special);

            obj.upDown = three(arr.slice(0, -1), function (e) {
                e = Number(e);
                if (e === 49) {
                    return special > 24 ? special + '' : '';
                } else {
                    return e > 24 ? e + '' : '';
                }
            }, 6, "updown");

            obj.oddEven = three(arr.slice(0, -1), function (e) {
                e = Number(e);
                if (e === 49) {
                    return special % 2 === 0 ? special + '' : '';
                } else {
                    return e % 2 === 0 ? e + '' : '';
                }
            }, 6, "oddeven");
            return obj;
        },
        GD11X5: function (item, arr) {
            var obj = {};
            obj.sumBigSmall = bigSmall(item.sum, 31, "zhi", { big: "总大", small: "总小" }, 30); // 总和大小
            obj.balls = item.result.split(",");
            obj.lastBigSmall = bigSmall(item.sum, 5, "wei", { big: "总尾大", small: "总尾小" }); // 总尾大小
            /// 单个号码的大小
            obj.OneBigSmall = function (num) {
                num = Number(num);
                if (num === 11) {
                    return showTag("和");
                } else if (num >= 6) {
                    return showTag("大", "b");
                } else {
                    return showTag("小", "r");
                }
            }
            /// 单个号码的单双
            obj.OneOddEven = function (num) {
                return Number(num) === 11 ? showTag("和") : (Number(num) % 2 === 0 ? showTag("双", "b") : showTag("单", "r"));
            }

            var special = item.result.match(/\d+$/)[0] * 1;
            obj.upDown = three(arr.slice(0, -1), function (e) {
                e = Number(e);
                if (e === 11) {
                    return special > 5 ? special + '' : '';
                } else {
                    return e > 5 ? e + '' : '';
                }
            }, 4, "updown");

            obj.oddEven = three(arr.slice(0, -1), function (e) {
                e = Number(e);
                if (e === 11) {
                    return special % 2 === 0 ? special + '' : '';
                } else {
                    return e % 2 === 0 ? e + '' : '';
                }
            }, 4, "oddeven");
            return obj;
        },
        GDKS: function (item, arr) {
            var obj = {};
            obj.sumBigSmall = bigSmall(item.sum, 85, "zhi", { big: "总大", small: "总小" }, true); // 总和大小
            obj.balls = item.result.split(",");
            obj.lastBigSmall = bigSmall(item.sum, 5, "wei", { big: "总尾大", small: "总尾小" }); // 总尾大小
            var special = item.result.match(/\d+$/)[0] * 1;
            obj.specialBigSmall = special >= 11 ? showTag("大", "b") : showTag("小", "r");
            obj.specialOddEven = special % 2 === 0 ? showTag("双", "b") : showTag("单", "r");
            obj.specialLastBigSmall = bigSmall(special, 5, 'wei', { big: "尾大", small: "尾小" });
            obj.specialCombSum = compute(String(special).split('')) % 2 === 0 ? showTag("合双", "b") : showTag("合单", "r");

            obj.upDown = three(arr, function (e) {
                return Number(e) > 10 ? e : '';
            }, 8, "updown");

            obj.oddEven = three(arr, function (e) {
                return Number(e) % 2 === 0 ? e : '';
            }, 8, "oddeven");

            obj.OneBigSmall = function (data) {
                return bigSmall(data, 11, 'zhi', { big: '大', small: '小' });
            }
            obj.OneOddEven = function (data) {
                return Number(data) % 2 === 0 ? showTag("双", "b") : showTag("单", "r");
            }
            obj.OneCombOddEven = function (data) {
                return compute(data.split('')) % 2 === 0 ? showTag("双", "b") : showTag("单", "r");
            }
            obj.OneLastBigSmall = function (data) {
                return bigSmall(Number(data), 5, 'wei', { big: '尾大', small: '尾小' });
            }
            return obj;
        },
        GXKS: function (item, arr) {
            var obj = {};
            var sixi = {
                '_1_2_3_4_5_': '福',
                '_6_7_8_9_10_': '禄',
                '_11_12_13_14_15_': '寿',
                '_16_17_18_19_20_': '喜'
            };
            obj.sumBigSmall = bigSmall(item.sum, 56, "zhi", { big: "总大", small: "总小", he: "和-和" }, true); // 总和大小
            obj.sumOddEven = (function () {

                return item.sum % 2 === 0 ? showTag("总双", "b") : showTag("总单", "r");

            })();
            obj.balls = arr;
            obj.lastBigSmall = bigSmall(item.sum, 5, "wei", { big: "总尾大", small: "总尾小" }); // 总尾大小
            obj.sixi = function (data) {
                if (Number(data) === 21) return '输-和';
                data = '_' + data + '_';
                var text = '';
                $.each(sixi, function (a, b) {
                    a.indexOf(data) > -1 && (text = b);
                });
                return text;
            }
            obj.OneBigSmall = function (data) {
                data = $.isArray(data) ? Number(data[0]) : Number(data);
                return data === 21 ? showTag("输-和") : (data >= 11 ? showTag("大", "b") : showTag("小", "r"));
            }
            obj.OneOddEven = function (data) {
                data = $.isArray(data) ? Number(data[0]) : Number(data);
                return data === 21 ? showTag("输-和") : (data % 2 === 0 ? showTag("双", "b") : showTag("单", "r"));
            }
            obj.OneCombOddEven = function (data) {
                data = $.isArray(data) ? Number(data[0]) : Number(data);
                return data === 21 ? showTag("输-和") : (compute(String(data).split('')) % 2 === 0 ? showTag("合双", "b") : showTag("合单", "r"));
            }
            obj.OneLastBigSmall = function (data) {
                data = $.isArray(data) ? Number(data[0]) : Number(data);
                return data === 21 ? showTag("输-和") : bigSmall(data, 5, 'wei', { big: "尾大", small: "尾小" });
            }

            var special = item.result.match(/\d+$/)[0] * 1;
            obj.upDown = three(arr.slice(0, -1), function (e) {
                e = Number(e);
                if (e === 21) {
                    return special > 10 ? special + '' : '';
                } else {
                    return e > 10 ? e + '' : '';
                }
            }, 4, "updown");
            obj.oddEven = three(arr.slice(0, -1), function (e) {
                e = Number(e);
                if (e === 21) {
                    return special % 2 === 0 ? special + '' : '';
                } else {
                    return e % 2 === 0 ? e + '' : '';
                }
            }, 4, "oddeven");
            return obj;
        },
        SSC: function (item, arr) {
            var obj = {};
            obj.balls = arr;
            obj.sumBigSmall = compute(arr) >= 23 ? showTag("总大", "b") : showTag("总小", "r");
            obj.OneBigSmall = function (data) {
                return Number(data) >= 5 ? showTag("大", "b") : showTag("小", "r");
            }
            obj.OneOddEven = function (data) {
                return Number(data) % 2 === 0 ? showTag("双", "b") : showTag("单", "r");
            }
            obj.before = ssc(arr.slice(0, 3));
            obj.middle = ssc(arr.slice(1, 4));
            obj.behind = ssc(arr.slice(2));
            return obj;
        },
        BJPK10: function (item, arr) {
            var obj = {};
            obj.balls = arr;
            obj.combFirstSecond = Number(arr[0]) + Number(arr[1]);
            obj.combFirstSecondOddEven = obj.combFirstSecond === 11 ? BJPKSGYHZ11 == 2 ? showTag("单", "r") : showTag("和") : (obj.combFirstSecond % 2 === 0 ? showTag("双", "b") : showTag("单", "r"));
            obj.combFirstSecondBigSmall = obj.combFirstSecond === 11 ? BJPKSGYHZ11 == 2 ? showTag("小", "r") : showTag("和") : (obj.combFirstSecond > 11 ? showTag("大", "b") : showTag("小", "r"));
            obj.oneBigSmall = function (data) {
                return Number(data) >= 6 ? showTag("大", "b") : showTag("小", "r");
            }
            obj.oneOddEven = function (data) {
                return Number(data) % 2 === 0 ? showTag("双", "b") : showTag("单", "r");
            }
            obj.pk = function (data) {
                if (data < 5) {
                    return Number(arr[data]) > Number(arr[9 - data]) ? showTag("龙", "b") : showTag("虎", "r");
                } else {
                    return '';
                }
            }
            return obj;
        },
        GXK3: function (item, arr) {
            var obj = {};
            obj.balls = arr;
            obj.sumBigSmall = item.sum >= 11 ? showTag("大", "b") : showTag("小", "r");
            return obj;
        },
        PCDD: function (item, arr) {
            var obj = {};
            obj.resultList = item.result.split(',');
            obj.bigSmall = item.sum < 14 ? '<b style="color:#2EA514">小</b>' : '<b style="color:#ff5500">大</b>';
            obj.evenOdd = item.sum % 2 == 0 ? '<b style="color:#ff5500">双</b>' : '<b style="color:#2EA514">单</b>';
            var leopard = true;
            for (var i = 0; i < obj.resultList.length - 1; i++) {
                if (obj.resultList[i] != obj.resultList[i + 1]) {
                    leopard = false;
                    break;
                }
            }
            obj.leopard = leopard ? '' : '<span style="color:#ccc;">---</span>'; '<span style="color:#666;">豹子【' + obj.resultList[0] + '】</span>'
            return obj;
        }
    };

    /// 前三、中三、后三
    /// arr:{Array}
    function ssc(arr) {
        arr = arr.sort(function (a, b) {
            return Number(a) - Number(b);
        });
        $.each(arr, function (a, b) {
            arr[a] = Number(b);
        });
        if (arr[0] === arr[1] && arr[0] === arr[2]) {
            return '豹子';
        } else if ((arr[0] + 1 === arr[1] && arr[1] + 1 === arr[2]) || /^(019)|(089)$/.test(arr.join(''))) {
            return '顺子';
        } else if (arr.unique().length === 2) {
            return '对子';
        } else if (arr[0] + 1 === arr[1] || arr[1] + 1 === arr[2] || /^0\d9$/.test(arr.join(''))) {
            return '半顺';
        } else {
            return '杂六';
        }
    }

    /// 与大小相关的属性
    /// sum:{Number}    和值
    /// bigVal:{Number} 为大的条件值
    /// type:{String}   玩法名
    /// he:{Boolen}     是否为有和
    function bigSmall(sum, bigVal, type, options, he) {
        switch (type) {
            // 值大小（总和大小、大小）
            case "zhi":
                if (he === undefined) {
                    return sum >= bigVal ? showTag(options.big, "b") : showTag(options.small, "r");
                } else {
                    return sum === (bigVal - 1) ? showTag(options.he ? options.he : "和") : (sum >= bigVal ? showTag(options.big, "b") : showTag(options.small, "r"));
                }
                /// 尾大小（总尾大小、合尾大小）
            case "wei":
                var last = Number(String(sum).slice(-1));
                return last >= bigVal ? showTag(options.big, "b") : showTag(options.small, "r");

        }
    }

    /// 龙虎斗
    function pk(long, hu, arr, he) {
        var long = Number(arr[long - 1]), hu = Number(arr[hu - 1]);
        if (long === he || hu === he) {
            return showTag("和");
        } else if (long > hu) {
            return showTag("龙", "r");
        } else {
            return showTag("虎", "b");
        }
    }

    function viewmodel() {
        this.list = function (data) {
            $.each(data, function (index, item) {
                var arr = [];
                /// 去掉号码开头的0
                $.each(item.result.split(','), function (a, b) {
                    arr.push(String(Number(b)));
                });
                item.result = arr.join(',');

                //var arr = item.result.split(',');
                /// 所有游戏可共用的属性
                item.sum = compute(arr); // 总和
                if (GameCode !== "GXK10") {
                    item.sumOddEven = item.sum % 2 === 0 ? showTag("总双", "b") : showTag("总单", "r");// 总和单双
                }
                switch (GameCode) {
                    case "LHC":
                        item.pk = function (long, hu) {
                            return pk(long, hu, arr, 49);
                        }
                        $.extend(item, ExtendAttr.SIX(item, arr));
                        break;
                    case "11X5":
                        item.pk = function (long, hu) {
                            return pk(long, hu, arr, 11);
                        }
                        $.extend(item, ExtendAttr.GD11X5(item, arr));
                        break;
                    case "GDK10":
                    case "CQK10":
                        item.pk = function (long, hu) {
                            return pk(long, hu, arr);
                        }
                        $.extend(item, ExtendAttr.GDKS(item, arr));
                        break;
                    case "GXK10":
                        item.pk = function (long, hu) {
                            return pk(long, hu, arr, 21);
                        }
                        $.extend(item, ExtendAttr.GXKS(item, arr));
                        break;
                    case "SSC":
                        item.pk = function (long, hu) {
                            var long = Number(arr[long - 1]), hu = Number(arr[hu - 1]);
                            if (long === hu) {
                                return showTag("和");
                            } else if (long > hu) {
                                return showTag("龙", "r");
                            } else {
                                return showTag("虎", "b");
                            }
                        }
                        $.extend(item, ExtendAttr.SSC(item, arr));
                        break;
                    case "PK10":
                        $.extend(item, ExtendAttr.BJPK10(item, arr));
                        break;
                    case "K3":
                        $.extend(item, ExtendAttr.GXK3(item, arr));
                        break;
                    case "PCDD":
                        $.extend(item, ExtendAttr.PCDD(item, arr));
                        break;
                }

            });
            this.listItem(data);
        };
        this.listItem = ko.observableArray();
        this.tpl = ko.observable("Tema-tpl");
        this.tabnav = function (t, css, data) {
            this.tpl(t);
            this.css(css);
        }
        this.css = ko.observable("a");

        this.changeGame = function ($data, event) {
            window.location.href = U('/lottery/log') + '&id=' + event.target.value;
        }
        this.second = ko.observable('-'); //自动刷新
        this.secondTxt = ko.observable('-');        
        this.Timer = null;  //定时器
        this.secondChange = function () {
            var that = this;
            if (that.second() && that.second() != '-') {
                clearInterval(that.Timer)
                that.comTimer();
                //panelOptions.second = that.second(); /// 保存自动刷新的状态
            } else {
                clearInterval(that.Timer);
                that.secondTxt(that.second());
                //delete panelOptions.second; /// 删除自动刷新的状态
            }
        }
       
        this.comTimer = function () {
            var that = this;
            if (that.Timer) {
                clearInterval(this.Timer);
                that.Timer = null;
            }
            that.secondTxt(that.second());
            var second = Number(that.second());
            that.Timer = setInterval(function () {
                $("#btnRelaod").val("刷新");
                second--;                
                if (second <= 0) {
                    second = that.second();
                    $("#btnRelaod").val("刷新中");
                    that.search();                    
                }
                that.secondTxt(second);
            }, 1000);
        }

        /*this.start = ko.observable();
        this.end = ko.observable();*/
        this.periodNum = ko.observable().extend({ numeric: "" });
        this.search = function (data) {
            $("#btnRelaod").val("刷新中");
            //var start = this.start();
            //var end = this.end();
            var periodNum = this.periodNum();
            //page.Search({ start: this.start() || '', end: this.end() || '', period: this.periodNum() || "" });
			page.Search({ dtrange: $('#dtrange').val(), period: this.periodNum() || "" });
            setTimeout(function () { $("#btnRelaod").val("刷新"); }, 1000)
            return false;
        }
        this.lotteryDate = function () {
            $.dialog({
                title: '搅珠日期表',
                padding: 0,
                content: '<iframe frameborder="0" src="http://special.hkjc.com/root2/marksix/info/ch/mark6/fixtures.asp" width="635" height="280" scrolling="no"></iframe>'
            });
        }
    }

    var page;
    $(function () {
        page = new Page(document.getElementById("ResultMain"), U('api/lottery/result2') + '&gameID=' + gameid, viewmodel);
        /*$("#ResultMain").css({
            height: document.documentElement.clientHeight - 10,
            overflow: 'auto'
        });
        $(window).resize(function () {
            $("#ResultMain").css({
                height: document.documentElement.clientHeight - 10
            });
        });*/
    });

    ko.extenders.numeric = function (target, options) {
        target.subscribe(function (newValue) {
            target(newValue.replace(/[^\d]+/g, ''));
        });
        return target;
    }
})(Page);